import { _decorator, Component, Sprite, Label, ParticleSystem2D, Node, Vec3, Material, v3, instantiate, tween, UIOpacity, UITransform, SpriteFrame, ParticleSystem, AudioClip } from 'cc';
const { ccclass, property } = _decorator;

import TurkishTetris_CardFunctions from "../Common/TurkishTetris_CardFunctions";
import TurkishTetris_GameConfig from "../../../../hall/Data/TurkishTetris_GameConfig";
import { TurkishTetris_GameData } from "../../../../hall/Data/TurkishTetris_GameData";
import { CardType } from "../../../../hall/Data/TurkishTetris_GameEnum";
import TurkishTetris_GameManager from "../Manager/TurkishTetris_GameManager";
import TurkishTetris_UIManager from "../Manager/TurkishTetris_UIManager";
import TurkishTetris_GamePanel from "../UI/TurkishTetris_GamePanel";
import { bdlMgr } from "../../../../../../Script/Manager/BundleManager_S";
import { TurkishTetris_GameStorage } from "../../../../hall/Data/TurkishTetris_GameStorage";

@ccclass('TurkishTetrisCardGroup')
export default class TurkishTetris_CardGroup extends Component {
        //    /** 填充节点 */
        @property(Sprite)
        icon: Sprite | null = null;
        @property(Label)
        Label_score: Label | null = null;
        @property(Label)
        Label_super: Label | null = null;
        @property(ParticleSystem2D)
        ParticleSystem_explode: ParticleSystem2D | null = null;
       
        @property(Node)
        flash: Node | null = null;
        @property(Node)
        FlashFrame: Node | null = null;
        @property(Node)
        CutAnimation: Node | null = null;
        id: number = 0;
        x: number = 0;
        y: number = 0;
        length: number = 1;
        type: CardType = CardType.Normal;
        //    // type: number = 0;
        color: number = 0;
        targetX: number = 0;
        newPosition: Vec3;
        initPosition: Vec3;
        cardAlpha: Node | null = null;
        isDead: boolean = false;
        //    // 特殊道具砖块是否已经释放
        isItemCast: boolean = false;
        cardTypeString = ["普通", "雷电", "切割"];
        //    // CardType[CardType.Super_1]: "雷电",
        bOperated: boolean = false;
        originalMaterials: Material[] = [];

        @property(Material)
        public material_normal: Material | null = null;
        @property(Material)
        public material_gray: Material | null = null;

        //    // 初始化
        init(_id: number, _type: CardType, _x: number, _y: number, _length: number, _color: number, _targetX: number) {
                this.id = _id;
                this.type = _type;
                this.x = _x;
                this.y = _y;
                this.length = _length;
                this.color = _color;
                this.targetX = _targetX;

                // this.originalMaterials = this.icon.getMaterials().slice(); // 复制数组
                this.originalMaterials = this.icon.sharedMaterials.slice();


                this.node.active = false;
                this.Init();

                // this.initWidthAndHeight(XXL_GameConfig.size, XXL_GameConfig.size);
                // this.InitPosition();

                this.AddListener();

                this.Label_score.node.active = false;

                // this.cardTypeString[CardType.Super_1] = "雷电1";
                // this.Spine_explode.node.active = false;
                this.ParticleSystem_explode.node.active = false;
                this.FlashFrame.active = false;
        }
        CreateCardAlpha() {
                this.cardAlpha = instantiate(this.node);
                this.cardAlpha.active = true;
                this.cardAlpha.getComponent(UIOpacity).opacity = 150;
                this.cardAlpha.parent = this.node.parent;
                this.cardAlpha.position = this.node.position;
        }
        GetNodeWorldPostation(_node: Node): Vec3 {
                let pos: Vec3 = v3();
                if (_node.parent == null) {
                        pos = v3(_node.getPosition());
                } else {
                        // pos = v3(_node.parent.convertToWorldSpaceAR(_node.getPosition()));
                        pos = _node.getWorldPosition();
                }
                return pos;
        }
        AddListener() {
                this.node.on(Node.EventType.TOUCH_START, this.TOUCH_START, this);
                this.node.on(Node.EventType.TOUCH_MOVE, this.TOUCH_MOVE, this);
                this.node.on(Node.EventType.TOUCH_END, this.TOUCH_END, this);
                this.node.on(Node.EventType.TOUCH_CANCEL, this.TOUCH_END, this);
        }
        TOUCH_START(t) {
                // console.log(this.x, this.y, this.length);

                if (this.y < 0) {
                        return;
                }
                if (!TurkishTetris_GameData.IsCanOperate) {
                        return;
                }
                if (TurkishTetris_GameData.IsMouseDown) {
                        // 不支持多点
                        return;
                }

                TurkishTetris_GameData.IsMouseDown = true;
                this.bOperated = true;

                const location = t.getLocation();

                this.initPosition = this.node.position;

                TurkishTetris_GameData.StartPos = location;
                TurkishTetris_UIManager.Instance.move_bg.active = true;
                // TurkishTetris_UIManager.Instance.move_bg.x = this.node.x;
                TurkishTetris_UIManager.Instance.move_bg.position = v3(this.node.position.x, TurkishTetris_UIManager.Instance.move_bg.position.y, TurkishTetris_UIManager.Instance.move_bg.position.z);
                TurkishTetris_UIManager.Instance.move_bg.getComponent(UITransform).width = TurkishTetris_GameConfig.size * this.length;

                // console.log(this.node.width, this.x, this.y, this.node.position.x, this.node.position.y);

                this.CreateCardAlpha();
        }
        TOUCH_MOVE(t) {
                // 必须点击了移动才算
                if (!this.bOperated) {
                        return;
                }

                if (this.y < 0) {
                        return;
                }
                if (!TurkishTetris_GameData.IsCanOperate) {
                        return;
                }

                if (TurkishTetris_GameData.IsMouseDown === true) {
                        const delta = t.getUIDelta();
                        const position = this.node.position;
                        this.node.setPosition(position.x + delta.x, position.y);




                        // const location = t.getLocation();

                        // // console.log(`location2`, location.x, location.y);

                        // TurkishTetris_GameData.CurrentPos = location;
                        // // let diff = v3(TurkishTetris_GameData.CurrentPos.sub(TurkishTetris_GameData.StartPos));
                        // let diff = TurkishTetris_GameData.CurrentPos.clone().subtract(TurkishTetris_GameData.StartPos);

                        let diff = delta

                        // console.log(`StartPos`, XXL_GameData.StartPos.x, XXL_GameData.StartPos.y);
                        // console.log(`CurrentPos`, XXL_GameData.CurrentPos.x, XXL_GameData.CurrentPos.y);
                        // console.log(`diff`, diff.x, diff.y);

                        let left = TurkishTetris_CardFunctions.GetRowL(this);
                        let right = TurkishTetris_CardFunctions.GetRowR(this);
                        // console.log("left-right", left, right);

                        let leftx = this.GetPositionXByX(left + 1);
                        let rightx = this.GetPositionXByX(right - this.length);
                        // console.log("leftx", leftx, rightx);

                        // let pos = v3(this.initPosition.x + diff.x, this.initPosition.y, this.initPosition.z); // this.initPosition.add(diff);
                        // this.node.position = pos;

                        if (this.node.position.x < leftx) {
                                this.node.position = v3(leftx, this.node.position.y, this.node.position.z);
                        }
                        if (this.node.position.x > rightx) {
                                this.node.position = v3(rightx, this.node.position.y, this.node.position.z);
                        }

                        {
                                // this.move_bg.x = this.node.x;
                                const x_new = this.GetXByX(this.node.position.x);
                                let x = -TurkishTetris_GameConfig.W / 2 + this.node.getComponent(UITransform).width / 2 + TurkishTetris_GameConfig.size * x_new;
                                // TurkishTetris_UIManager.Instance.move_bg.x = x;
                                TurkishTetris_UIManager.Instance.move_bg.position = v3(x, TurkishTetris_UIManager.Instance.move_bg.position.y, TurkishTetris_UIManager.Instance.move_bg.position.z);
                        }
                }
        }
        TOUCH_END() {
                if (!this.bOperated) {
                        return;
                }

                if (this.y < 0) {
                        return;
                }
                if (!TurkishTetris_GameData.IsCanOperate) {
                        return;
                }

                TurkishTetris_GameData.IsMouseDown = false;
                this.bOperated = false;

                TurkishTetris_UIManager.Instance.move_bg.active = false;

                if (this.cardAlpha) {
                        this.cardAlpha.destroy();
                        this.cardAlpha = null;
                }

                const x_new = this.GetXByX(this.node.position.x);

                let isTarget: boolean = x_new === this.targetX;
                // if (!GameData.IsNewGuide() || GameData.gameMode != GAME_MODE_ENUM.NORMAL) {
                isTarget = true;
                // }

                // console.log(x_new, this.x);
                if (x_new !== this.x && isTarget) {
                        // if (GameData.gameMode == GAME_MODE_ENUM.NORMAL && GameData.IsNewGuide()) {
                        // TurkishTetris_GuidePanel.Instance.ShowOff();

                        TurkishTetris_GameStorage.data.guideStep++;
                        TurkishTetris_GameStorage.saveData();
                        // }

                        this.x = x_new;

                        TurkishTetris_GameData.IsCanOperate = false;
                        TurkishTetris_GameManager.Main(6);
                }

                this.InitPosition();
        }
        GetXByX(x_pos: number) {
                let x = (x_pos - (-TurkishTetris_GameConfig.W / 2 + this.node.getComponent(UITransform).width / 2)) / TurkishTetris_GameConfig.size + 0.5;
                let x_int = Math.floor(x);
                // console.log(`xx`, x, x_int);

                return x_int;
        }
        //    // 初始化单元宽高
        initWidthAndHeight(cardWidth?: number, cardHeight?: number) {
                if (cardWidth) this.node.getComponent(UITransform).width = this.icon.node.getComponent(UITransform).width = cardWidth * this.length;
                if (cardHeight) this.node.getComponent(UITransform).height = this.icon.node.getComponent(UITransform).height = cardHeight;
        }
        //    // 初始化位置
        InitPosition(_x = null, _y = null) {
                let xx = _x !== null ? _x : this.x;
                let yy = _y !== null ? _y : this.y;

                let x = -TurkishTetris_GameConfig.W / 2 + this.node.getComponent(UITransform).width / 2 + TurkishTetris_GameConfig.size * xx;
                let y = -TurkishTetris_GameConfig.H / 2 + this.node.getComponent(UITransform).height / 2 + this.node.getComponent(UITransform).height * yy;
                this.node.position = v3(x, y, 0);
        }
        //    //
        GetPositionXByX(_x) {
                let x = -TurkishTetris_GameConfig.W / 2 + this.node.getComponent(UITransform).width / 2 + TurkishTetris_GameConfig.size * _x;
                return x;
        }
        //    // // 初始化位置
        movePosition(callback: Function = null) {
                let x = -TurkishTetris_GameConfig.W / 2 + this.node.getComponent(UITransform).width / 2 + TurkishTetris_GameConfig.size * this.x;
                let y = -TurkishTetris_GameConfig.H / 2 + this.node.getComponent(UITransform).height / 2 + this.node.getComponent(UITransform).height * this.y;
                this.newPosition = v3(x, y, 0);

                tween(this.node)
                        .to(0.16, { position: this.newPosition })
                        .delay(0.02)
                        .call(() => {
                                // // if (GameData.gameMode == GAME_MODE_ENUM.NORMAL) {
                                // if (TurkishTetris_GameStorage.data.guideStep === 0) {
                                //     TurkishTetris_GuidePanel.Instance.ShowOn();
                                //     TurkishTetris_GuidePanel.Instance.Move_1();
                                // }
                                // if (TurkishTetris_GameStorage.data.guideStep === 1) {
                                //     TurkishTetris_GuidePanel.Instance.ShowOn();
                                //     TurkishTetris_GuidePanel.Instance.Move_2();
                                // }
                                // // }

                                if (callback) {
                                        callback();
                                }
                        })
                        .start();
        }
        //    // 假设 this.ParticlePrefab 是粒子预设
        async ExplodeByLength() {
                const length = this.length; // 砖块长度
                const startX = this.node.position.x - (this.node.getComponent(UITransform).width / 2) + TurkishTetris_GameConfig.size / 2;

                for (let i = 0; i < length; i++) {
                        const particleNode = instantiate(this.ParticleSystem_explode.node);
                        particleNode.parent = TurkishTetris_UIManager.Instance.Root_effect;
                        particleNode.active = true;

                        // 根据砖块长度均匀计算粒子位置
                        const posX = startX + i * TurkishTetris_GameConfig.size;
                        const posY = this.node.position.y;
                        particleNode.setPosition(posX, posY);

                        // const ps = particleNode.getComponent(ParticleSystem);
                        const ps = particleNode.getComponent(ParticleSystem2D);




                        let name = ``;
                        // name = `block_00${this.color + 1}_${this.length}`;
                        name = `block_00${this.color + 1}_${1}`;
                        // const sp = await TurkishTetris_bdlMgr.getRes<SpriteFrame>(TurkishTetris_Consts.BundleName.SPRITE, `ui/block/${name}`, SpriteFrame);
                        const sp = await bdlMgr.getRes<SpriteFrame>('TurkishTetris_Sprite', `ui/block/${name}/spriteFrame`, SpriteFrame);
                        ps.spriteFrame = sp;


                        ps.resetSystem(); // 播放粒子系统





                        // 播放完后销毁
                        this.scheduleOnce(() => {
                                particleNode.destroy();
                        }, ps.duration + ps.life + ps.lifeVar);
                }
        }
        DestroyAnimation(callback: Function = null) {
                if (this.isDead) {
                        return;
                }

                // bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, `audio/merge sound`, AudioClip).then(res => {
                //         if (res) {
                //                 AudioManager.Instance.playSFX(res, false);
                //                 // audioEngine.setVolume(audioId, 0.6);
                //         }
                // });

                this.isDead = true;
                let gameMode = 1
                // console.log("消除格子", this.x, this.y);
                if (gameMode == 1) {
                        const score = TurkishTetris_CardFunctions.GetScore(this.length);
                        // GameData.Score += score;
                        // TurkishTetris_GameData.curScore += score;
                        TurkishTetris_GameData.SetScore(TurkishTetris_GameData.GetScore() + score);

                        if (TurkishTetris_GameStorage.data.high_score < TurkishTetris_GameData.GetScore()) {
                                TurkishTetris_GameStorage.data.high_score = TurkishTetris_GameData.GetScore();
                                TurkishTetris_GameStorage.saveData();
                        }
                        // LocalStorage.getInstance().setInt(HallConst.LocalStorageKey.curScore, GameData.curScore);

                        // // GameData.UpdateScore();
                        // TurkishTetris_GameFunctions.LevelUp();

                        TurkishTetris_GamePanel.Instance.Refresh();

                        // this.Label_score.string = `${score}`;
                        // this.Label_score.node.active = true;
                        // this.Label_score.node.parent = this.node.parent;
                        // this.Label_score.node.position = this.node.position;
                        // const node_Label_score = this.Label_score.node;
                        // tween(node_Label_score)
                        //     .by(0.5, { y: 5 }, { easing: "" })
                        //     .to(1, { opacity: 0 }, { easing: "" })
                        //     .call(() => {
                        //         node_Label_score.destroy();
                        //     })
                        //     .start();



                        tween(this.node.getComponent(UIOpacity))
                                .to(0.1, { opacity: 0 })
                                .call(async () => {
                                        // this.ParticleSystem_explode.node.active = true;
                                        // const startPst = TurkishTetris_UIManager.Instance.Root_effect.convertToNodeSpaceAR(this.ParticleSystem_explode.node.convertToWorldSpaceAR(Vec3.ZERO));
                                        // this.ParticleSystem_explode.node.parent = TurkishTetris_UIManager.Instance.Root_effect;
                                        // this.ParticleSystem_explode.node.setPosition(startPst);


                                        await this.ExplodeByLength();



                                        // let name = ``; // `block_00${this.color + 1}_${this.length}`;
                                        // // const name = `block_00${2}_${this.length}`;
                                        // // if (this.type === CardType.Normal) {
                                        // //     name = `block_00${this.color + 1}_${this.length}`;
                                        // // } else if (this.type === CardType.Super_1) {
                                        // //     name = `block_super_001_${this.length}`;
                                        // //     this.flash.active = true;
                                        // // } else if (this.type === CardType.Super_2) {
                                        // //     name = `block_super_002_${this.length}`;
                                        // // }
                                        // name = `block_00${this.color + 1}_${this.length}`;
                                        // // name = `block_00${this.color + 1}_${1}`;
                                        // // TurkishTetris_bdlMgr.getRes<SpriteFrame>(TurkishTetris_Consts.BundleName.SPRITE, `ui/block/${name}`, SpriteFrame).then(img => {

                                        // const sp = await TurkishTetris_bdlMgr.getRes<SpriteFrame>(TurkishTetris_Consts.BundleName.SPRITE, `ui/block/${name}`, SpriteFrame);

                                        // this.ParticleSystem_explode.spriteFrame = sp;

                                        // CommonFunction.SetNodeParent(XXL_UIManager.Instance.Root_effect, this.ParticleSystem_explode.node);

                                        this.node.destroy();
                                        if (callback) {
                                                callback();
                                        }

                                        // bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, `audio/符文碎裂`, AudioClip).then(res => {
                                        //         if (res) {
                                        //                 SSS_AudioManager.Instance.playSFX(res, false);
                                        //                 // audioEngine.setVolume(audioId, 0.6);
                                        //         }
                                        // });
                                })
                                // .to(1, { opacity: 255 }, { easing: "" })
                                .call(() => { })
                                .start();
                } else if (gameMode == 2) {
                        // XXL_GamePanel.Instance.Refresh();

                        tween(this.node.getComponent(UIOpacity))
                                .to(0.1, { opacity: 0 })
                                .call(() => {
                                        // plan3
                                        if (this.x == 0) {
                                                // let startPst = TurkishTetris_UIManager.Instance.Root_effect.convertToNodeSpaceAR(this.node.convertToWorldSpaceAR(Vec3.ZERO));
                                                let worldPos = this.node.getComponent(UITransform)!.convertToWorldSpaceAR(Vec3.ZERO);
                                                let startPst = TurkishTetris_UIManager.Instance.Root_effect.getComponent(UITransform)!.convertToNodeSpaceAR(worldPos);
                                        }
                                        this.node.destroy();
                                        if (callback) {
                                                callback();
                                        }
                                })
                                // .to(1, { opacity: 255 }, { easing: "" })
                                .call(() => { })
                                .start();
                }
        }
        Destroy() {
                this.node.destroy();
        }

        ToGray() {
                // let m = this.icon.getMaterials();
                let m = this.originalMaterials;
                console.log(`m`, m);
                // this.icon.setMaterial(0, m[1]);
                // this.icon.setMaterialInstance(m[1], 0,);

                this.icon.material = this.material_gray;
        }

        ToColor() {
                let m = this.originalMaterials;
                console.log(`m0--`, m);
                // this.icon.setMaterial(0, m[0]);
                // this.icon.setMaterialInstance(m[0], 0,);
                this.icon.material = this.material_normal;
        }

        Init() {
                // const color = XXL_GameConfig.colors[this.color];
                // this.icon.node.color = new Color().fromHEX(color);

                let name = ``; // `block_00${this.color + 1}_${this.length}`;
                // const name = `block_00${2}_${this.length}`;

                this.flash.active = false;
                this.CutAnimation.active = false;
                if (this.type === CardType.Normal) {
                        name = `block_00${this.color + 1}_${this.length}`;
                } else if (this.type === CardType.Super_1) {
                        name = `block_super_001_${this.length}`;
                        this.flash.active = true;
                } else if (this.type === CardType.Super_2) {
                        name = `block_super_002_${this.length}`;
                        this.CutAnimation.active = true;
                        this.CutAnimation.children[0].active = true;
                        this.CutAnimation.children[1].active = false;
                }

                // LoaderManager.getInstance().loadRes(
                //     `ui/block/${name}`,
                //     gen_handler((img: SpriteFrame) => {
                //         // console.log("img", img);

                //         if (this && this.node) {
                //             this.icon.spriteFrame = img;

                //             // this.icon.sizeMode = Sprite.SizeMode.TRIMMED;
                //             this.icon.node.position = v3(0, 0, 0);

                //             this.initWidthAndHeight(XXL_GameConfig.size, XXL_GameConfig.size);
                //             // console.log("initWidthAndHeight", this.x, this.y, XXL_GameConfig.size);

                //             this.InitPosition();

                //             this.node.active = this.y >= 0;
                //         }
                //     }, this),
                //     wwRes,
                //     SpriteFrame


                // );

                bdlMgr.getRes<SpriteFrame>('TurkishTetris_Sprite', `ui/block/${name}/spriteFrame`, SpriteFrame).then(img => {
                        if (this && this.node) {
                                this.icon.spriteFrame = img;

                                // this.icon.sizeMode = Sprite.SizeMode.TRIMMED;
                                this.icon.node.position = v3(0, 0, 0);

                                this.initWidthAndHeight(TurkishTetris_GameConfig.size, TurkishTetris_GameConfig.size);
                                // console.log("initWidthAndHeight", this.x, this.y, XXL_GameConfig.size);

                                this.InitPosition();

                                this.node.active = this.y >= 0;
                        }
                });

                // bdlMgr.getRes<SpriteFrame>(SSS_Consts.BundleName.SPRITE, `main/material/icon/${item_data.icon}`, SpriteFrame).then(res => { this.icon.spriteFrame = res });


                this.Label_super.node.active = false;

                // this.FlashFrame.scaleX = this.length;
                this.FlashFrame.scale = v3(this.length, this.FlashFrame.scale.y, this.FlashFrame.scale.z);

                if (TurkishTetris_GameData.gameMode == 1) {
                        this.ParticleSystem_explode.spriteFrame = this.ParticleSystem_explode.getComponentsInChildren(Sprite)[this.color].spriteFrame;
                }

                // this.Label_super.node.active = this.type !== CardType.Normal;
                // this.Label_super.string = this.cardTypeString[this.type];

                // this.cardTypeString[CardType[CardType.Super_1]] = "雷电1";
                // this.cardTypeString[CardType[CardType.Super_2]] = "雷电2";
        }
        //    // 切割
        CutBlock(_callback: Function = null) {
                if (this.length <= 1) {
                        if (_callback) {
                                _callback();
                        }

                        return;
                }

                // AudioPlayer.getInstance().playSound("sound/qiege", false, hallFunc.xwResBundle);

                this.CutAnimation.active = true;
                this.CutAnimation.children[0].active = false;
                this.CutAnimation.children[1].active = true;

                this.scheduleOnce(() => {
                        const row = TurkishTetris_GameData.arrCardGroups[this.y];

                        // console.log(`row-22`, row);

                        const x_1 = this.x;
                        const length_1 = 1;
                        const x_2 = this.x + length_1;
                        const length_2 = this.length - length_1;
                        const y = this.y;
                        const id = this.id;
                        const color = this.color;
                        const cardType: CardType = this.type;

                        this.Destroy();
                        TurkishTetris_CardFunctions.RemoveOneCardGroup(this);

                        // console.log(`row-22`, row);

                        // for (let index = 0; index < row.length; index++) {
                        //     const element = row[index];
                        //     // console.log("element", element.x, element.y, element.length);
                        // }

                        const cardGroup_1: TurkishTetris_CardGroup = TurkishTetris_CardFunctions.CreateCardGroup(id, cardType, x_1, y, length_1, color, -1);
                        // GameData.arrCardGroups[y].push(cardGroup_1);
                        row.push(cardGroup_1);

                        const cardGroup_2: TurkishTetris_CardGroup = TurkishTetris_CardFunctions.CreateCardGroup(id, cardType, x_2, y, length_2, color, -1);
                        // GameData.arrCardGroups[y].push(cardGroup_2);
                        row.push(cardGroup_2);

                        function compare(a, b) {
                                if (a.x > b.x) return 1;
                                if (b.x > a.x) return -1;
                                return 0;
                        }
                        row.sort(compare);

                        if (_callback) {
                                _callback();
                        }
                }, 0.6);
        }
        RefreshLabel() { }
        RefreshIcon() { }
        ToMapData() {
                let data: any = {};
                data.id = this.id;
                data.type = this.type;
                data.x = this.x;
                data.y = this.y;
                data.length = this.length;
                data.color = this.color;
                data.targetX = this.targetX;
                return data;
        }
}